<template>
  <view>
    <nav-bar title="订单管理" class="nav-bar" />
    <view class="head">
      <screen-search
        class="screen-search"
        @submit="handleSearch"
        @blur="handleSearchBlur"
      ></screen-search>
      <scroll-tab
        :style="{ top: searchHeight + navBarHeight + 'px' }"
        class="scroll-tab"
        :activeTab="tabActive"
        :tabData="tabData"
        @tabMsg="tabMsg"
      ></scroll-tab>
      <view
        class="industry-bar"
        :style="{ top: searchHeight + navBarHeight + scrollTabHeight + 'px' }"
      >
        <view
          v-for="(item, index) in industryList"
          :key="index"
          @click="indusBtn(item)"
          class="indus"
          :class="{
            indusActive: listConfig.deliveryTypes.includes(item.value),
          }"
          >{{ item.label }}</view
        >
      </view>
    </view>

    <scroll-view
      scroll-y
      class="content"
      @scrolltolower="handleNextPage"
      v-if="computedOrderList.length > 0"
      :style="{
        height: `calc(100vh - ${
          searchHeight + navBarHeight + scrollTabHeight + industryBarHeight
        }px )`,
        top:
          searchHeight +
          navBarHeight +
          scrollTabHeight +
          industryBarHeight +
          'px',
      }"
    >
      <view
        class="card"
        v-for="(item, index) in computedOrderList"
        :key="index"
      >
        <view class="merch" @click="jumpDetail(item.orderNo)">
          <view class="rig">
            <view class="top">
              <view class="name">{{ item.storeName }}</view>
              <view class="indus">{{ typeOptions[item.deliveryString] }}</view>
            </view>
            <view class="btm" v-if="item.appointmentTime"
              >预计送达时间：{{ item.appointmentTime }}</view
            >
          </view>
          <view class="lef">
            <view>
              <view
                v-if="item.deliveryString === ORDER_DELIVER_METHOD.PUB_LOCAL"
              >
                <view
                  v-if="
                    item.status === ORDER_STATUS.UNDERWAY &&
                    item.subStatusInt === ORDER_PUB_LOCAL_STATUS.WAITING_SEND
                  "
                >
                  未配送
                </view>
                <view
                  v-else-if="
                    item.status === ORDER_STATUS.UNDERWAY &&
                    item.subStatusInt === ORDER_PUB_LOCAL_STATUS.SENDING
                  "
                >
                  配送中
                </view>
                <view v-else>
                  {{ ORDER_STATUS_TEXT[item.status] }}
                </view>
              </view>
              <view v-else>
                {{ ORDER_STATUS_TEXT[item.status] }}
              </view>
            </view>
            <view class="cause">超时自动取消</view>
          </view>
        </view>
        <view class="user">
          <view class="rig">
            <view
              class="top"
              v-if="item.deliveryString === ORDER_DELIVER_METHOD.PUB_LOCAL"
            >
              <view class="name">{{ item.delivery.userName }}</view>
              <view class="phone">{{ item.delivery.phone }}</view>
            </view>
            <view class="top" v-else>
              <view class="name">{{ item.customerName }}</view>
              <view class="phone">{{ item.memberPhone }}</view>
            </view>
            <view
              class="btm"
              v-if="item.deliveryString === ORDER_DELIVER_METHOD.PUB_LOCAL"
              >{{ item.delivery.province }}{{ item.delivery.city
              }}{{ item.delivery.country }}{{ item.delivery.street
              }}{{ item.delivery.detail }}</view
            >
          </view>
          <view
            @click="makeCall(item.delivery.phone || item.memberPhone)"
            class="lef"
            ><view class="iconfont icon-dianhua1"></view
          ></view>
        </view>
        <view @click="jumpDetail(item.orderNo)" class="con">
          <scroll-view class="scroll-view" scroll-x="true" scroll-left="0">
            <view
              v-for="(sItem, sIndex) in item.items"
              :key="sIndex"
              class="scroll-view-item"
            >
              <image :src="ossBaseUrl + sItem.coverImg" mode=""></image>
            </view>
          </scroll-view>
          <view class="num">{{ item.goodsNum }}件</view>
        </view>
        <view class="price-info">
          <view class="price">
            <view>应收：</view>
            <view class="money">
              ￥
              <span style="font-size: 36rpx">{{
                item.payFee | formatMoneyStart
              }}</span>
              {{ item.payFee | formatMoneyLast }}
            </view>
          </view>
          <view class="oper">
            <view
              class="operBtn"
              v-if="
                item.status === ORDER_STATUS.UNDERWAY &&
                (item.deliveryString === ORDER_DELIVER_METHOD.PUB_PACK ||
                  item.deliveryString === ORDER_DELIVER_METHOD.PUB_HALL_FOOD)
              "
              ><u-button
                type="primary"
                :customStyle="btnGetCode"
                :plain="true"
                @click="handleFinishOrder(item)"
                text="完成"
              ></u-button
            ></view>
            <view
              class="operBtn"
              v-if="
                item.status === ORDER_STATUS.UNDERWAY &&
                item.deliveryString !== ORDER_DELIVER_METHOD.PUB_LOCAL
              "
              ><u-button
                @click="handleWriteOff(item)"
                type="primary"
                :customStyle="btnGetCode"
                text="核销"
              ></u-button
            ></view>
            <block
              v-if="item.deliveryString === ORDER_DELIVER_METHOD.PUB_LOCAL"
            >
              <view
                class="operBtn"
                v-if="
                  item.status === ORDER_STATUS.UNDERWAY &&
                  item.subStatusInt === ORDER_PUB_LOCAL_STATUS.WAITING_SEND
                "
                ><u-button
                  @click="handleDelivery(item)"
                  type="primary"
                  :customStyle="btnGetCode"
                  text="配送"
                ></u-button>
              </view>
              <view
                class="operBtn"
                v-if="
                  item.status === ORDER_STATUS.UNDERWAY &&
                  item.subStatusInt === ORDER_PUB_LOCAL_STATUS.SENDING
                "
              >
                <u-button
                  type="primary"
                  :customStyle="btnGetCode"
                  @click="handleFinishSendingOrder(item)"
                  text="送达"
                  >送达</u-button
                >
              </view>
            </block>
          </view>
        </view>
      </view>
      <u-loadmore line marginTop="10" marginBottom="40" :status="loadmore" />
      <view class="blank-box"></view>
    </scroll-view>
    <view
      class="content"
      v-else
      :style="{
        top:
          searchHeight +
          navBarHeight +
          scrollTabHeight +
          industryBarHeight +
          'px',
      }"
    >
      <xh-empty />
    </view>
  </view>
</template>

<script>
import scrollTab from "@/components/pageComponents/sp-order/scroll-tab";
import screenSearch from "@/components/pageComponents/sp-order/screen-search";
import {
  orderDelivered,
  orderDelivery,
  orderList,
  orderWriteOff,
} from "@/service/api/sp-order/index.js";
import {
  ORDER_PUB_LOCAL_STATUS,
  ORDER_DELIVER_METHOD,
  ORDER_DELIVER_METHOD_TEXT,
  ORDER_STATUS,
  ORDER_STATUS_TEXT,
} from "@/pages/sp-order/const/order";
import { DELIVER_METHOD_NUMBER } from "@/const/order";

export default {
  components: { scrollTab, screenSearch },
  data() {
    return {
      ORDER_PUB_LOCAL_STATUS,
      ORDER_STATUS,
      ORDER_STATUS_TEXT,
      ORDER_DELIVER_METHOD,
      ossBaseUrl: process.env.VUE_APP_BASE_FileUrl,
      searchHeight: 50,
      navBarHeight: 60,
      scrollTabHeight: 45,
      industryBarHeight: "",
      tabData: [
        {
          name: "全部",
          value: "",
          icon: "",
        },
        {
          name: "待支付",
          value: ORDER_STATUS.WAITING,
          icon: "",
        },
        {
          name: "进行中",
          value: ORDER_STATUS.UNDERWAY,
          isSort: true,
          // icon: "icon-biaotou-kepaixu",
          sort: 0,
        },
        {
          name: "已完成",
          value: ORDER_STATUS.FINISH,
          icon: "",
        },
        {
          name: "已退款",
          value: ORDER_STATUS.CANCEL,
          icon: "",
        },
      ],
      tabActive: 0,
      industry: 100, // <100 就餐，否则配送
      industryList: [
        {
          label: ORDER_DELIVER_METHOD_TEXT.PUB_HALL_FOOD,
          value: DELIVER_METHOD_NUMBER.PUB_HALL_FOOD,
        },
        {
          label: ORDER_DELIVER_METHOD_TEXT.PUB_PACK,
          value: DELIVER_METHOD_NUMBER.PUB_PACK,
        },
        {
          label: ORDER_DELIVER_METHOD_TEXT.PUB_LOCAL,
          value: DELIVER_METHOD_NUMBER.PUB_LOCAL,
        },
      ],
      // industryList: ["堂食", "打包", "同城配送"],
      indusIndex: "",

      btnGetCode: {
        width: "140rpx", //驼峰命名注意
        height: "60rpx",
      },

      // 订单数据
      orderList: [],
      hasNextPage: false,
      loadmore: "loadmore",
      listConfig: {
        orderNo: "", //订单号
        pageNum: 1,
        pageSize: 10,
        type: "", //就餐方式
        sortWay: 0, //0倒序 1正序
        orderStatus: "",
        deliveryTypes: [4, 5, 7],
        memberPhone: "",
        beginTime: "",
        endTime: "",
        pubShopId: "",
      },
      typeOptions: {
        PUB_LOCAL: "同城配送",
        PUB_HALL_FOOD: "堂食",
        PUB_PACK: "打包",
        PUB_SHOP_CONSUME: "到店消费",
        PUB_SELF_PICKUP: "自提",
      },
    };
  },
  filters: {
    formatMoneyStart(e) {
      return String(e / 100).split(".")[0] + ".";
    },
    formatMoneyLast(e) {
      return String(e / 100).split(".")[1] || "00";
    },
  },
  computed: {
    computedOrderList({ orderList, listConfig }) {
      if (!listConfig?.orderStatus) {
        return orderList;
      }
      return orderList.filter((v) => v.status === listConfig.orderStatus);
    },
  },
  mounted() {
    this.uGetRectFun();
    this.getOrderListFun();
    this.tabActive = Number(this.$Route?.query?.active) || 0;
  },
  methods: {
    tabMsg(val) {
      this.tabActive = this.tabData.findIndex((v) => v.value === val.value);
      if (
        //禁止重复刷新
        !val.isSort &&
        this.listConfig.orderStatus === val.value
      )
        return;
      if (
        this.listConfig.orderStatus === "UNDERWAY" &&
        val.value === "UNDERWAY"
      ) {
        const tempSortWay = uni.$u.deepClone(this.listConfig).sortWay;
        this.listConfig.sortWay = tempSortWay === 0 ? 1 : 0;
        this.tabData.map((v) => {
          if (v.isSort) {
            v.sort = tempSortWay === 0 ? 1 : 0;
          }
        });
      } else {
        this.listConfig.sortWay = 0;
        this.tabData.map((v) => {
          if (v.isSort) {
            v.sort = 0;
          }
        });
      }
      this.resetOrderListPageConfig();
      this.listConfig.orderStatus = val.value;
      this.$nextTick(() => {
        this.getOrderListFun();
      });
    },
    // 获取组件高度
    uGetRect(selector, all) {
      return new Promise((resolve) => {
        uni
          .createSelectorQuery()
          .in(this)
          [all ? "selectAll" : "select"](selector)
          .boundingClientRect((rect) => {
            if (all && Array.isArray(rect) && rect.length) {
              resolve(rect);
            }
            if (!all && rect) {
              resolve(rect);
            }
          })
          .exec();
      });
    },
    uGetRectFun() {
      const search = this.uGetRect(".screen-search");
      const navBar = this.uGetRect(".nav-bar");
      const scrollTab = this.uGetRect(".scroll-tab");
      const industryBar = this.uGetRect(".industry-bar");

      Promise.all([search, navBar, scrollTab, industryBar]).then((res) => {
        console.log("组件高度", res);
        this.searchHeight = res[0].height;
        this.navBarHeight = res[1].height;
        this.scrollTabHeight = res[2].height;
        this.industryBarHeight = res[3].height;
      });
    },

    // 类型
    indusBtn(item) {
      if (this.listConfig.deliveryTypes.includes(item.value)) {
        const tempIndusIndex = this.listConfig.deliveryTypes.findIndex(
          (i) => i === item.value
        );
        this.listConfig.deliveryTypes.splice(tempIndusIndex, 1);
      } else {
        this.listConfig.deliveryTypes.push(item.value);
      }
      this.resetOrderListPageConfig();
      this.$nextTick(() => {
        this.getOrderListFun();
      });
    },
    resetOrderListPageConfig() {
      this.listConfig.pageNum = 1;
      this.orderList = [];
    },
    // 拨打电话
    makeCall(phone) {
      uni.makePhoneCall({
        phoneNumber: phone,
      });
    },
    // 跳转详情
    jumpDetail(orderCode) {
      uni.navigateTo({
        url: `pages/sp-order/pages/orderDetail/index?&orderCode=${orderCode}`,
        events: {
          orderStatus: (res) => {
            this.orderList.map((order) => {
              if (order.orderNo === res?.orderNo) {
                order.status = res?.orderStatus;
              }
            });
          },
        },
        success: (res) => {
          res.eventChannel.emit("orderList", {
            orderCode: orderCode,
          });
        },
      });

      // this.$Router.push({
      //   name: "orderDetail",
      //   params: {
      //     orderCode: orderCode,
      //   },
      // });
    },
    handleSearchBlur(e) {
      this.listConfig.memberPhone = e;
      this.resetOrderListPageConfig();
      this.$nextTick(() => {
        this.getOrderListFun();
      });
    },
    // 订单列表
    getOrderListFun() {
      const {
        memberPhone,
        sortWay,
        orderNo,
        pageNum,
        pageSize,
        deliveryTypes,
        orderStatus,
        pubShopId,
        beginTime,
        endTime,
      } = this.listConfig;
      this.loadmore = "loading";
      let params = {
        beginTime, //开始时间
        businessName: "", //商户名称
        endTime, //结束时间
        memberPhone, //手机号
        mercNo: "", //商户编号
        sortWay,
        orderNo, //订单号
        pageNum,
        pageSize,
        deliveryTypes,
        paymentMethod: "", //支付方式
        pubOrderStatus: orderStatus, //状态（WAITING: 待支付, UNDERWAY: 进行中, FINISH: 已完成, CANCEL:已取消, AFTER_SALES: 已售后）
        pubShopId, //公域门店id
        // type: this.listConfig.type, //配送方式（同城配送:PUB_LOCAL 堂食:PUB_HALL_FOOD 打包:PUB_PACK 到店消费:PUB_SHOP_CONSUME 自提:PUB_SELF_PICKUP）
      };
      orderList(params).then((res) => {
        console.log("订单列表", res);
        if (res.list) {
          res.list.map((i) => {
            i.goodsNum = 0;
            i.items.forEach((item) => {
              i.goodsNum += item.num;
            });
          });
        }
        this.orderList = [...this.orderList, ...res.list];
        this.loadmore = res.hasNextPage ? "loadmore" : "nomore";
        this.hasNextPage = res.hasNextPage;
      });
    },
    //搜索
    handleSearch(form) {
      const { startDate, endDate, storeValue } = form;
      this.listConfig.beginTime = startDate;
      this.listConfig.endTime = endDate;
      this.listConfig.pubShopId = storeValue;
      this.resetOrderListPageConfig();
      this.$nextTick(() => {
        this.getOrderListFun();
      });
    },
    handleNextPage() {
      // console.log("触底");
      if (!this.hasNextPage) return;
      this.listConfig.pageNum += 1;
      this.$nextTick(() => {
        this.getOrderListFun();
      });
    },
    //完成
    async handleFinishOrder(item) {
      const orderNo = item?.orderNo;
      const res = await orderWriteOff({ orderNoOrCode: orderNo }).catch(
        (err) => {
          uni.showToast({
            title: err.msg,
            icon: "none",
          });
        }
      );
      if (res?.code === 0) {
        uni.showToast({
          title: "成功",
          icon: "success",
        });
      }
      //完成后手动变更状态，不重新获取，避免数据白屏
      this.orderList.map((order) => {
        if (order.orderNo === orderNo) {
          order.status = ORDER_STATUS.FINISH;
        }
      });
    },
    //核销
    async handleWriteOff(item) {
      const {
        orderNo,
        delivery: { takeNo },
      } = item;
      uni.navigateTo({
        url: `pages/scan/index?type=pubUserWriteOff&takeNo=${takeNo}`,
        events: {
          orderStatus: (res) => {
            this.orderList.map((order) => {
              if (order.orderNo === res?.data) {
                order.status = ORDER_STATUS.FINISH;
              }
            });
          },
        },
        success: (res) => {
          res.eventChannel.emit("writeOff", {
            orderNo,
          });
        },
      });
      this.$Router.push({
        name: "scan",
        params: {
          type: "pubUserWriteOff",
          takeNo,
        },
      });
      //需要扫公域用户小程序的二维码进行核销
    },
    //去配送
    async handleDelivery(item) {
      const orderNo = item?.orderNo;
      const res = await orderDelivery({
        orderNo,
      }).catch((err) => {
        uni.showToast({
          title: err.msg,
          icon: "none",
        });
      });
      if (res?.code === 0) {
        uni.showToast({
          title: "配送成功",
          icon: "success",
        });
      }
      //完成后手动变更状态，不重新获取，避免数据白屏
      this.orderList.map((order) => {
        if (order.orderNo === orderNo) {
          order.subStatusInt = ORDER_PUB_LOCAL_STATUS.SENDING;
        }
      });
    },
    //送达
    async handleFinishSendingOrder(item) {
      const orderNo = item?.orderNo;
      const res = await orderDelivered({ orderNo: orderNo }).catch((err) => {
        uni.showToast({
          title: err.msg,
          icon: "none",
        });
      });
      if (res?.code === 0) {
        uni.showToast({
          title: "成功",
          icon: "success",
        });
      }
      //完成后手动变更状态，不重新获取，避免数据白屏
      this.orderList.map((order) => {
        if (order.orderNo === orderNo) {
          order.status = ORDER_STATUS.FINISH;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.head {
  overflow: hidden;
  .screen-search {
    position: fixed;
    left: 0;
    z-index: 10;
    width: 100%;
    background-color: white;
  }
  .scroll-tab {
    position: fixed;
    left: 0;
    z-index: 9;
    width: 100%;
    overflow: hidden;
    background-color: white;
    display: flex;
    align-items: center;
  }
  .industry-bar {
    background-color: #f7f7f7;
    position: fixed;
    left: 0;
    z-index: 9;
    width: 100%;
    overflow: hidden;
    display: flex;
    justify-items: flex-start;
    align-items: center;
    padding: 30rpx 0;
    .indus {
      border: 1px solid #ffb72f;
      border-radius: 8rpx;
      text-align: center;
      font-size: 29rpx;
      padding: 11rpx 19rpx;
      box-sizing: border-box;
      margin-left: 30rpx;
      color: #ffb72f;
    }
    .indusActive {
      color: white;
      background-color: #ffb72f;
    }
  }
}
.blank-box {
  width: 686rpx;
  height: 50rpx;
}
.content {
  padding: 0 20rpx;
  box-sizing: border-box;
  position: fixed;
  left: 0;
  z-index: 9;
  width: 100%;
  //height: 67vh;
  overflow-y: scroll;
  .card {
    background-color: white;
    margin-bottom: 26rpx;
    .merch {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #f8efcf;
      padding: 28rpx 23rpx;
      box-sizing: border-box;
      .rig {
        .top {
          display: flex;
          justify-items: flex-start;
          .name {
            font-size: 29rpx;
            font-weight: bold;
            color: #181818;
            max-width: 250rpx;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-box-orient: vertical;
            word-break: break-all;
          }
          .indus {
            font-size: 22rpx;
            color: #a68453;
            background: #feda95;
            border-radius: 8rpx;
            padding: 7rpx 13rpx;
            box-sizing: border-box;
            margin-left: 17rpx;
          }
        }
        .btm {
          font-size: 24rpx;
          color: #131313;
          opacity: 0.7;
          margin-top: 20rpx;
        }
      }
      .lef {
        font-size: 27rpx;
        color: #a1a1a0;
        font-weight: 500;
        text-align: center;
        .cause {
          font-size: 22rpx;
        }
      }
    }
    .user {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 28rpx 23rpx;
      box-sizing: border-box;
      .rig {
        .top {
          display: flex;
          justify-items: flex-start;
          .name {
            font-size: 29rpx;
            font-weight: bold;
            color: #131313;
          }
          .phone {
            font-size: 29rpx;
            margin-left: 32rpx;
            color: #131313;
          }
        }
        .btm {
          font-size: 29rpx;
          color: #131313;
          margin-top: 23rpx;
        }
      }
      .lef {
        background-color: #ffb72f;
        border-radius: 50%;
        overflow: hidden;
        width: 49rpx;
        height: 49rpx;
        text-align: center;
        line-height: 49rpx;
        .iconfont {
          color: white;
          font-size: 29rpx;
        }
      }
    }
    .con {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .scroll-view {
        white-space: nowrap;
        flex: 6;
        overflow: hidden;

        .scroll-view-item {
          width: 150rpx;
          height: 150rpx;
          overflow: hidden;
          margin-left: 16rpx;
          display: inline-block;
          //border: 1rpx dashed #8f8f8f;
          image {
            width: 100%;
            height: 100%;
          }
        }
      }

      .num {
        flex: 1;
        text-align: center;
        font-size: 27rpx;
        font-weight: 500;
        color: #888888;
      }
    }
    .price-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-top: 1rpx dashed #ececec;
      margin: 0 22rpx;
      margin-top: 40rpx;
      padding: 13rpx 0;
      overflow: hidden;
      .price {
        display: flex;
        justify-items: flex-start;
        font-weight: bold;
        align-items: center;
        .money {
          color: #f05357;
          font-size: 28rpx;
        }
      }
      .oper {
        display: flex;
        justify-content: space-between;
        overflow: hidden;
        .operBtn {
          margin-right: 35rpx;
          border-radius: 8rpx;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
